﻿using System.Security.Cryptography;
using Newtonsoft.Json;

namespace Admin.NET.Core.Helper;

public class DingtalkWebHookHelper
{
    private static async Task SendMarkdownMessage(string webhookUrl, string accessToken, string secret, string title,
        string markdownContent)
    {
        var timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds();
        var sign = ComputeSignature(secret, timestamp);

        var url = $"{webhookUrl}?access_token={accessToken}&timestamp={timestamp}&sign={sign}";

        using (var client = new HttpClient())
        {
            string jsonPayload;
            if (markdownContent.IndexOf("错", StringComparison.Ordinal) > -1)
            {
                var payload = new
                {
                    msgtype = "markdown",
                    markdown = new
                    {
                        title,
                        text = markdownContent
                    },
                    at = new
                    {
                        isAtAll = true
                    }
                };
                jsonPayload = JsonConvert.SerializeObject(payload);
            }
            else
            {
                var payload = new
                {
                    msgtype = "markdown",
                    markdown = new
                    {
                        title,
                        text = markdownContent
                    }
                };
                jsonPayload = JsonConvert.SerializeObject(payload);
            }

            var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");

            var response = await client.PostAsync(url, content);

            if (response.IsSuccessStatusCode)
                Console.WriteLine("Markdown message sent successfully!");
            else
                Console.WriteLine("Failed to send Markdown message. Status code: " + response.StatusCode);
        }
    }

    private static string ComputeSignature(string secret, long timestamp)
    {
        var stringToSign = $"{timestamp}\n{secret}";
        var secretBytes = Encoding.UTF8.GetBytes(secret);
        var stringToSignBytes = Encoding.UTF8.GetBytes(stringToSign);

        using (var hmac = new HMACSHA256(secretBytes))
        {
            var hashBytes = hmac.ComputeHash(stringToSignBytes);
            return Convert.ToBase64String(hashBytes);
        }
    }

    public static async Task SendMessagePlus(string markdownContent)
    {
        var webhookUrl = "https://oapi.dingtalk.com/robot/send";
        var title = "LuTools 通知";
#if DEBUG
        title += "(开发环境)";
        string accessToken = "dfd9380850560d21ad98f9612cfa94bea8f8b292d3dbd28451345ea4cfc2fa36";
        string secret = "SEC2b976a8096d9661ad4fd7dbbf73d6d8e222f9e2b8bd64a324c13efdf95799c8e";

        await SendMarkdownMessage(webhookUrl, accessToken, secret, title, markdownContent);

#else
        title += "";
        string accessToken = "e59031ce234c32fff4b5d71fa5b4b1a3e171a96a1fcef31aabd05a35a52b587f";
        string secret = "SECfa9c304740593f4b6abfc93038bad819d68b786450ec15b51ec07b78984e3ae5";

        await SendMarkdownMessage(webhookUrl, accessToken, secret, title, markdownContent);
#endif
    }

    public static async Task SendMessage(string markdownContent)
    {
        var webhookUrl = "https://oapi.dingtalk.com/robot/send";
        var title = "LuTools 通知";
#if DEBUG
        title += "(开发环境)";
        string accessToken = "dfd9380850560d21ad98f9612cfa94bea8f8b292d3dbd28451345ea4cfc2fa36";
        string secret = "SEC2b976a8096d9661ad4fd7dbbf73d6d8e222f9e2b8bd64a324c13efdf95799c8e";
        await SendMarkdownMessage(webhookUrl, accessToken, secret, title, markdownContent);

#else
        title += "";
        string accessToken = "6e422b7dd12d46c903d47662172ccf620380d8abfa121f191a8681bbb2707c72";
        string secret = "SEC699e9248172e50b2d75c0538b093451ac6078996bff407f879eb5a1e4a8ba9d7";

        await SendMarkdownMessage(webhookUrl, accessToken, secret, title, markdownContent);
#endif
    }
}